package org.dhy.elasticsearch;

import org.apache.http.HttpHost;
import org.dhy.elasticsearch.ElasticConfigProperties.ElasticConfig;
import org.dhy.elasticsearch.client.ESClientSpringFactory;
import org.dhy.elasticsearch.interfaces.AbstractEsRepository;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author longye
 */
@Configuration
@ConditionalOnClass(ESClientSpringFactory.class)
@EnableConfigurationProperties(ElasticConfig.class)
public class ElasticSearchAutoConfiguration {

    @Bean(initMethod = "init", destroyMethod = "close")
    public ESClientSpringFactory esClientSpringFactory(ElasticConfig elasticConfig) {
        try {
            final String[] hosts = elasticConfig.getHosts();
            if (hosts == null || hosts.length == 0) {
                final HttpHost httpHost = new HttpHost("localhost", 9200, "http");
                return ESClientSpringFactory.build(new HttpHost[]{httpHost});
            }
            HttpHost[] httpHosts = Arrays.stream(hosts).map(HttpHost::create).toArray(HttpHost[]::new);
            return ESClientSpringFactory.build(httpHosts,
                    elasticConfig.getConnectTimeoutMillis(),
                    elasticConfig.getSocketTimeoutMillis(),
                    elasticConfig.getConnectionRequestTimeoutMillis(),
                    elasticConfig.getMaxConnTotal(),
                    elasticConfig.getMaxConnPerRoute()
            );
        } finally {
            System.out.println("init esClientSpringFactory complete!");
        }
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(ESClientSpringFactory esClientSpringFactory) {
        return esClientSpringFactory.getRhlClient();
    }

    @Bean
    public RestClient restClient(ESClientSpringFactory esClientSpringFactory) {
        return esClientSpringFactory.getClient();
    }
}